﻿// UninstallDlg.cpp: 实现文件
//
#include "StdAfx.h"

#pragma once

#include "AutoUpdate.h"
#include "UninstallDlg.h"
#include "afxdialogex.h"

#include <afxwin.h>

#include <thread>
#include "FileUtil.h"
#include "Config.h"
#include "SystemUtil.h"
#include "CommonConst.h"
using namespace std;
// UninstallDlg 对话框

IMPLEMENT_DYNAMIC(UninstallDlg, CDialogEx)

UninstallDlg::UninstallDlg(CWnd* pParent /*=nullptr*/)
	: CDialogEx(IDD_DLGUninstall, pParent)
{

}

UninstallDlg::~UninstallDlg()
{
}

void UninstallDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialogEx::DoDataExchange(pDX);
	//  DDX_Control(pDX, IDOK, btnOK);

	DDX_Control(pDX, ID_ProgressUninstall, uninstallProgress);
}


BEGIN_MESSAGE_MAP(UninstallDlg, CDialogEx)
END_MESSAGE_MAP()


// UninstallDlg 消息处理程序


BOOL UninstallDlg::OnInitDialog()
{
	CDialogEx::OnInitDialog();


	//btnOK.SetFaceColor(RGB(128, 128, 128), true);
	SetWindowText("卸载");

	auto result = AfxMessageBox("是否确认卸载?", MB_YESNO);
	if (result != IDYES) {
		exit(0);
	}


	//进度条颜色
	uninstallProgress.SendMessage(PBM_SETBARCOLOR, 0, RGB(50, 205, 50));//前景色
	uninstallProgress.SendMessage(PBM_SETBKCOLOR, 0, RGB(204, 204, 204));//背景色

	CRect rectDlg;
	GetClientRect(rectDlg);//获得窗体的大小

	//获取标题栏高度
	auto titleHeight = SystemUtil::GetTitleHeight();

	CRect marginRect;
	GetDlgItem(ID_ProgressUninstall)->GetWindowRect(&marginRect);

	CRect mainImgRect;
	GetDlgItem(IDC_UninstallImg)->GetWindowRect(&mainImgRect);
	ScreenToClient(&mainImgRect);
	GetDlgItem(IDC_UninstallImg)->MoveWindow(mainImgRect.left, mainImgRect.top, rectDlg.Width(), marginRect.top - titleHeight - 20, true);

	Config::Load();

	//强制关闭
	FileUtil::TaskKill(Config::ProgrameName);

	Unstall();

	return TRUE;  // return TRUE unless you set the focus to a control
				  // 异常: OCX 属性页应返回 FALSE
}


void UninstallDlg::Unstall()
{

	uninstallThread = AfxBeginThread(UnstallAsync, this, THREAD_PRIORITY_NORMAL, 0, NULL);
}
UINT __cdecl UninstallDlg::UnstallAsync(LPVOID lparam) {
	UninstallDlg* dlg = (UninstallDlg*)lparam;

	if (dlg != nullptr) {

		dlg->UnstallHandleAsync();

		dlg->PostMessageA(WM_CLOSE, NULL, NULL);
	}

	return 0;
}
void UninstallDlg::UnstallHandleAsync() {

	////强制关闭
	//FileUtil::TaskKill(Config::ProgrameName);

	auto installPath = SystemUtil::GetRegKeyString(CONST_DISPLAYNAME, "InstallLocation");
	if (installPath == "") {
		exit(0);
	}

	SystemUtil::Uninstall(CONST_DISPLAYNAME);
	SystemUtil::DeleteDesktopShotCut(CONST_DISPLAYNAME);

	SystemUtil::RemoveDir(installPath.GetString(), &uninstallProgress);

}

void UninstallDlg::SetPos(short pos, short total) {
	uninstallProgress.SetRange(0, total);
	uninstallProgress.SetPos(pos);

}
